import hashlib
import json
import random
import requests

from application import app


class MemberService(object):

    # cookie加密
    @staticmethod
    def geneAuthCode(member_info):
        m = hashlib.md5()
        str = '%s-%s-%s' % (member_info.id, member_info.salt, member_info.status)
        m.update(str.encode('utf-8'))
        return m.hexdigest()

    @staticmethod
    def geneSalt():
        seed = "1234567890abcdefghijklmnopqrstuvwxyz"
        sa = []
        for i in range(15):
            sa.append(random.choice(seed))
        salt = ''.join(sa).upper()
        return salt

    @staticmethod
    def getWechatOpenid(code):
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={' \
              '}&grant_type=authorization_code'.format(app.config['MINA_APP']['appid'], app.config['MINA_APP']['appsecret'], code)
        opresp = json.loads(requests.get(url).text)
        if 'openid' in opresp:
            openid = opresp['openid']
        return openid
